//app.js
App({
  config: {
    baseURL: 'http://wx-cloud-classroom.duans.top/apis',
    appId: 'wxcbb251aaa59a0012',
    appSecret: 'ee86cb2c0bfc3539708ece531c68eaa4'
  },
  globalData: {
    userInfo: wx.getStorageSync('userInfo'),
    openId: wx.getStorageSync('openId')
  },
  // 获取openid
  // https://api.weixin.qq.com/sns/jscode2session?appid=wxcbb251aaa59a0012&secret=ee86cb2c0bfc3539708ece531c68eaa4&js_code=001P8K2g2BnacF0L9b2g2TsK2g2P8K25&grant_type=authorization_code
  onLaunch(){
    if (!this.globalData.openId) {
      wx.login({
        success: (res) => {
          this.getOpenid(res.code);
        }
      })
    }
  },
  saveUserInfo(userInfo) {
    this.globalData.userInfo = userInfo;
    wx.setStorage({
      key: 'userInfo',
      data: userInfo,
      success: () => {
        wx.reLaunch({
          url: '/pages/index/index',
        })
      }
    });
  },
  getOpenid(code) {
    const appId = this.config.appId;
    const appSecret = this.config.appSecret;
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
    wx.request({
      url,
      success: (({
        data
      }) => {
        // console.log(data);
        wx.setStorage({
          data: data.openid,
          key: 'openid',
        })
      })
    })
  }
})